<?php
/**
 * Date: 2017/11/7
 * Time: 18:19
 * Author: zeronlee
 */
namespace App\Http\Controllers\Backend\Access;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Dompdf\Exception;
use Illuminate\Http\Request;
use App\Models\Access\User\User;
use App\Models\Access\Role\Role;
use App\Models\Ogz;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Traits\Base;
use App\Models\Access\User\UserExt;
use App\Models\Access\User\UserAddress;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    use Base;
    /**
     * 用户首页
     */
    public function index (){
        //每页显示数量
        $pageNum = 10;
        //模板
        return view('backend.access.userindex',['pageNum'=>$pageNum]);
    }
    /**
     * 异步查询
     */
    public function search(Request $request){
        $param = $request->input();
        $fields = ['u.*','o.id as ogz_id','o.name as ogz_name'];
        //多条件搜索
        $search = $param['search'];
        //默认值
        $search['value'] = empty($search['value']) ? '1&' : $search['value'];
        //搜索值按页面搜索框从左到右
        $filter = explode('&',$search['value']);
        $searchDisabled = false;
        if ($filter[0]==2){
            $searchDisabled = true;
        }
        //全局条件
        if (!$this->userIsSuperAdmin()){
            //只有超级管理员可以查看未设定机构的用户
            $filter[2] = ['ao.ogz_id',access()->hasOgzs($searchDisabled)];
        }
        //记录数
        $count = User::getCount($filter);

        //列表
        $users = User::getList($filter,[$param['start'],$param['length']],$fields);
        foreach ($users as $user){

            $user->email = empty($user->email) || filter_var($user->email,FILTER_VALIDATE_EMAIL) ? $user->email : decrypt_func($user->email,$user->name);
            $user->phone = empty($user->phone) || filter_var(intval($user->phone),FILTER_VALIDATE_INT) ? $user->phone : decrypt_func($user->phone,$user->name);
            $temp = User::withTrashed()->find($user->id);
            $user->roles_name = $temp->roles->implode('name',',');
            //是否绑定外部用户
            if (!$searchDisabled) {
                //禁用用户没有属性
                $user->attched = User::checkIsAttacted($user->id);
            }
        }
        $data = array('draw'=>$param['draw'],'recordsTotal'=>$count,'recordsFiltered'=>$count,'data'=>$users);

        return response()->json($data);
    }
    /**
     * 存储用户信息
     */
    public function add (Request $request){
        $res['code'] = 0;
        $this->validateForm($request);

        try{
            $user = new User();
            $user->insertRow($request);
        }catch (\Exception $e){
            $res['code'] = 500;
            $res['msg'] = $e->getMessage();
        }

        return response()->json($res);
    }

    /**
     * 数据验证
     */
    public function validateForm ($request) {
        $this->validate($request, [
            'name' => ['required',Rule::unique('users')->ignore($request->id)],
            'real_name' => 'required',
            'phone'=>'regex:/^1[34578][0-9]{9}$/',
            'email' => ['required',Rule::unique('users')->ignore($request->id),'email']
        ],[
            'name.required' => '请填写用户名',
            'name.unique' => '用户名已重复，请重新填写用户名信息',
            'real_name.required' => '请填写真实姓名',
            'phone.regex' => '请填写合法的手机号',
            'email.required' => '请填写邮箱',
            'email.unique' => '该邮箱已存在',
            'email.email' => '请填写合法的邮箱'
        ]);
    }

    /**
     * 一条完整用户集合信息
     */
    public function getRow (Request $request){
        $user = new User();
        $data['code'] = 0;
        $userRole = $userOgz = [];
        //用户及绑定角色
        $userRoles = $user->getUserRoles($request->uid);
        //用户及所在机构
        $userOgzs = $user->getUserOgzs($request->uid);

        $i = 0;
        foreach ($userRoles as $role) {
            $userRole[$i]['id'] = $role->id;
            $userRole[$i]['name'] = $role->name;
            $i++;
        }
        $j = 0;
        foreach ($userOgzs as $ogz) {
            $userOgz[$j]['id'] = $ogz->id;
            $userOgz[$j]['name'] = $ogz->name;
            $j++;
        }
        //角色集合
        $role = new Role();
        $roles = $role->getList();
        $data['roles'] = $roles;
        $data['userRoles'] = $userRole;
        //机构集合
        $fields = ['o.id','o.name','o.pid'];
        $ogzs = $this->getOgzs($fields,[0=>['o.deleted_at','==','NULL']]);
        $data['ogzs'] = $ogzs;
        $data['userOgzs'] = $userOgz;
        return response()->json($data);
    }

    /**
     * 全局数据验证
     */
    public function scopeValid ($data){
        $res = ['code'=>0];
        //user_id
        $users = $this->getUsers();
        $go = false;
        foreach ($users as $user){
            if ($user->id == $data['id']){
                $go = true;
            }
        }
        if (!$go){
            $res['code'] = 403;
            $res['msg'] = '没有权限操作该用户';
        }

        return $res;
    }
    /**
     * 获取有效的用户数据
     */
    public function getUsers (){
        $userFields = ['u.id','u.name as user_name','u.name'];
        $userWhere = [];
        if (!$this->userIsSuperAdmin()){
            $scopeWhere = $this->scopeFilter('ogz');
            $userWhere[2] = ['ao.ogz_id',$scopeWhere];
        }
        return User::getList($userWhere,[0,User::getCount($userWhere)],$userFields);
    }
    /**
     * 更新用户信息
     */
    public function update (Request $request){
        $data['code'] = 0;
        //user roles
        $user = new User();
        $this->validateForm($request);
        $valider = $this->scopeValid($request->input(),'update');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg'] = $valider['msg'];
        }else{
            try{
                $user->updateRow($request);
            }catch (\Exception $e){
                $data['code'] = 500;
                $data['msg'] = $e->getMessage();
            }
        }
        return response()->json($data);
    }

    /**
     * 删除用户信息
     */
    public function delete (Request $request){
        $data['code'] = 0;
        //软删除
        $valider = $this->scopeValid($request->input(),'del');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg'] = $valider['msg'];
        }else{
            $user = new User();
            if (!$user->deleteRow($request)){
                $data['code'] = 500;
                $data['msg'] = '服务器忙';
            }
        }
        return response()->json($data);
    }
    /**
     * 激活用户
     */
    public function active (Request $request){
        $data['code'] = 0;
        //软删除
        $valider = $this->scopeValid($request->input(),'del');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg'] = $valider['msg'];
        }else{
            $user = new User();
            if (!$user->activeRow($request)){
                $data['code'] = 500;
                $data['msg'] = '服务器忙';
            }
        }
        return response()->json($data);
    }
    /**
     * 基础信息
     */
    public function getExt (Request $request){

        $data['code'] = 0;

        $userExt = new UserExt();
        try{
            $data['data'] = $userExt->get($request);
        }catch (\Exception $e){
            $data['code'] = 500;
            $data['msg'] = $e->getMessage();
        }
        return response()->json($data);
    }
    /**
     * 收货地址
     */
    public function getAddress (Request $request){

        $data['code'] = 0;

        $userAddress = new UserAddress();
        try{
            $data['data'] = $userAddress->get($request);
        }catch (\Exception $e){
            $data['code'] = 500;
            $data['msg'] = $e->getMessage();
        }
        return response()->json($data);
    }
    /**
     * 绑定外部用户
     */
    public function attachRelation (Request $request){
        $data['code'] = 0;
        if ($request->id != auth()->user()->id){
            $data['code'] = 500;

            $data['msg'] = '非法操作';
        } else {

            $user = User::find($request->id);
            //查询绑定用户信息
            $toChange = $this->getUser($request->name,$request->pass);
            if (!$toChange->isEmpty()){

                $user->attachRelate(['id'=>$toChange->get('id')]);
                $data['msg'] = '操作成功';
            } else {
                $data['code'] = 500;
                $data['msg'] = '信息错误';
            }
        }
        return response()->json($data);
    }
    /**
     * 解绑外部用户
     */
    public function detachRelation (Request $request){
        $data['code'] = 0;
        if ($request->id != auth()->user()->id){
            $data['code'] = 500;

            $data['msg'] = '非法操作';
        } else {

            $user = User::find($request->id);
            //查询绑定用户信息
            $toChange = $this->getUser($request->name,$request->pass);
            if (!$toChange->isEmpty()){
                $user->detachRelate(['id'=>$toChange->get('id')]);
                $data['msg'] = '操作成功';
            } else {
                $data['code'] = 500;
                $data['msg'] = '信息错误';
            }
        }
        return response()->json($data);
    }
    /**
     * 用户信息安全处理
     */
    protected function getUser ($name,$pass) {
        //用户email和phone加密
        //用户名name和密码password没有encryption
        return User::getOneUser(['name'=>$name,'password'=>$pass]);
    }
}